<template>
  <el-tabs v-model="activeName" class="demo-tabs">
    <el-tab-pane label="老师" name="first">
              
      <div class="col-lg-12 grid-margin stretch-card">
              <div class="card">
                <div class="card-body">
                  <h4 class="card-title">软件学院老师列表</h4>
                  
                  <div class="table-responsive pt-3">
                    <table class="table table-bordered">
                      <thead>
                        <tr>
                          <th>
                            序号
                          </th>
                          <th>
                            姓名
                          </th>
                          <th>
                            性别
                          </th>
                          <th>
                            系别
                          </th>
                          <th>
                            电话
                          </th>
                          <th style="width: 41%;">
                            所授课程
                          </th>
                          <th style="width: 13%;">
                            操作
                          </th>
                        </tr>
                      </thead>
                      <tbody>
                        <tr v-for="(item,index) in teacherList" :key="index">
                          <td>
                            {{ index+1 }}
                          </td>
                          <td>
                            {{ item.teacher_name }}
                          </td>
                          <td>
                            {{ item.teacher_sex }}
                          </td>
                          <td>
                           {{ item.department }}
                          </td>
                          <td>
                            {{ item.phone }}
                          </td>
                          <td style="width: 41%;">
                            {{ item.courses }}
                          </td>
                          <td style="width: 13%;">
    <el-button type="button"  @click="getChatWindow(item.teacher_id,item.teacher_name)" class="btn btn-outline-primary btn-fw w-100">发送消息</el-button>
    <el-dialog v-model="dialogMessage[item.teacher_name]" :title="item.teacher_name" width="500">
       <div style="height: 500px;">
        <div class="h-3/4 overflow-auto border-y border-black"> 
          <div class="container">
              <ul>
                  <li v-for="(item1,index1) in messageList[item.teacher_name]" :key="index1">
                  <div class="row">
                    <div class="col-sm-12 my-2">
                        <p class="text-center mb-2">{{ item1.send_time }}</p>
                        <div :class="isSelf(item1.sender_id)">
                          <div class="col-2 col-sm-2 d-flex justify-content-center">
                            <el-avatar class="text-black bg-blue-300">{{ item1.sender_name }}</el-avatar>
                          </div>
                          <div class="d-flex align-items-center col-auto border rounded max-w-80">
                          <p class="m-0 mx-2">{{ item1.content }}</p>
                          </div>
                          </div>
                    </div>
                </div>
                  </li>
              </ul>
            </div>
        </div>
        <div class="flex h-1/4 justify-content-end rounded-bottom">
          <textarea @keyup.enter="sendMessageToService(item.teacher_id,item.teacher_name)" class="flex form-control p-0" id="exampleFormControlTextarea1" v-model="inputMessage" rows="2"></textarea>
          <button type="button" @click="sendMessageToService(item.teacher_id,item.teacher_name)" class="btn btn-outline-primary align-self-end m-3" style="position: absolute;">发送</button>
          <button type="button" @click="setDialog(item.teacher_name)" class="btn btn-outline-primary align-self-end my-3 mx-19" style="position: absolute;">退出</button>
        </div>
       </div>
     </el-dialog>
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>



    </el-tab-pane>
    <el-tab-pane label="学生" name="second">
      <div class="col-lg-12 grid-margin stretch-card">
              <div class="card">
                <div class="card-body">
                  <h4 class="card-title">软件学院学生列表</h4>
                 
                  <div class="table-responsive pt-3">
                    <table id="recent-purchases-listing" class="table dataTable no-footer" role="grid">
                      <thead>
                        <tr role="row">
                          <th class="sorting_asc" tabindex="0" aria-controls="recent-purchases-listing" rowspan="1" colspan="1" aria-sort="ascending" aria-label="Name: activate to sort column descending" style="width: 104.366px;">姓名</th>
                          <th class="sorting" tabindex="0" aria-controls="recent-purchases-listing" rowspan="1" colspan="1" aria-label="Status report: activate to sort column ascending" style="width:67.6607px">性别</th>
                          <th class="sorting" tabindex="0" aria-controls="recent-purchases-listing" rowspan="1" colspan="1" aria-label="Office: activate to sort column ascending" style="width: 160.929px;">专业</th>
                          <th class="sorting" tabindex="0" aria-controls="recent-purchases-listing" rowspan="1" colspan="1" aria-label="Price: activate to sort column ascending" style="width:180.116px;">兴趣爱好</th>
                          <th class="sorting" tabindex="0" aria-controls="recent-purchases-listing" rowspan="1" colspan="1" aria-label="Date: activate to sort column ascending" style="width: 153.188px;">科研经历</th>
                          <th class="sorting" tabindex="0" aria-controls="recent-purchases-listing" rowspan="1" colspan="1" aria-label="Gross amount: activate to sort column ascending" style="width: 155.188px;">操作</th>
                        </tr>
                      </thead>
                      <tbody>
                      <tr role="row" class="odd" v-for="(student,stuIndex) in studentList" :key="stuIndex">
                            <td class="sorting_1">{{ student.student_name }}</td>
                            <td>{{ student.student_sex }}</td>
                            <td>{{ student.major }}</td>
                            <td>{{ student.interest }}</td>
                            <td>{{ student.search_exper }}</td>
                            <td>
                              <el-button v-if="user_id!==student.student_id" type="button"  @click="getChatWindStu(student.student_id,student.student_name)" class="btn btn-outline-primary btn-fw w-100">发送消息</el-button>
    <el-dialog v-model="dialogMessageStu[student.student_name]" :title="student.student_name" width="500">
       <div style="height: 500px;">
        <div class="h-3/4 overflow-auto border-y border-black"> 
          <div class="container">
              <ul class="px-0">
                  <li v-for="(stuitem1,stuindex1) in messageList[student.student_name]" :key="stuindex1">
                  <div class="row">
                    <div class="col-sm-12 my-2">
                        <p class="text-center mb-2">{{ stuitem1.send_time }}</p>
                        <div :class="isSelf(stuitem1.sender_id)">
                          <div class="col-2 col-sm-2 d-flex justify-content-center">
                            <el-avatar class="text-black bg-blue-300">{{ stuitem1.sender_name }}</el-avatar>
                          </div>
                          <div class="d-flex align-items-center col-auto border rounded max-w-80">
                          <p class="m-0 mx-2">{{ stuitem1.content }}</p>
                          </div>
                          </div>
                    </div>
                </div>
                  </li>
              </ul>
            </div>
        </div>
        <div class="flex h-1/4 justify-content-end rounded-bottom">
          <textarea @keyup.enter="sendMessageToService(student.student_id,student.student_name)" class="flex form-control p-0" id="exampleFormControlTextarea1" v-model="inputMessage" rows="2"></textarea>
          <button type="button" @click="sendMessageToService(student.student_id,student.student_name)" class="btn btn-outline-primary align-self-end m-3" style="position: absolute;">发送</button>
          <button type="button" @click="setDialogStu(student.student_name)" class="btn btn-outline-primary align-self-end my-3 mx-19" style="position: absolute;">退出</button>
        </div>
       </div>
     </el-dialog>
                            </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
                </div>
              </div>
            </div>
    </el-tab-pane>
    
    <el-tab-pane label="科创项目" name="third">
      <button @click="drawer = true" class="btn btn-outline-primary">我的科创</button>

      <el-drawer v-model="drawer" title="I am the title" direction="ltr" :with-header="false">
        <span>科创信息</span>
        <table class="table">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">科创项目</th>
      <th scope="col">申请时间</th>
      <th scope="col">状态</th>
    </tr>
  </thead>
  <tbody>
    <tr v-for="(item,index) in studentProjectList" :key="index">
      <th scope="row">{{ index+1 }}</th>
      <td>{{ item.project_name }}</td>
      <td>{{ item.apply_time }}</td>
      <td>{{ item.apply_state }}</td>
    </tr>
  </tbody>
</table>
      </el-drawer>

      <el-carousel :interval="4000" type="card" height="400px">
        <el-carousel-item  v-for="(item,index) in projectList" :key="index">
          <div class="card w-100 h-100">
              <h3>{{ item.project_name }}</h3>
              <div class="mx-3">
                <p class="lead" style="font-size: 1em;">&nbsp;&nbsp; {{ item.introduce }}</p>
              </div>
              <div class="mx-3">
                <p style="font-size: 1em"><b>时间:</b>&nbsp;&nbsp; {{ item.start_time }}~{{ item.end_time }}</p>
                <i class="mr-5" style="font-size: 1em"><b>类别:</b>&nbsp;&nbsp;{{ item.project_type }}</i>
                <i style="font-size: 1em"><b>管理员:</b>&nbsp;&nbsp;{{ item.admin_name }}</i>
                <p class="mt-3"><b>要求：</b>{{ item.requirement }}</p>
              </div>
              <div class="demo-progress ml-4">
                <p><b>目前人数：</b>{{ item.exist_number }}/{{ item.all_number   }}</p>
                <el-progress :percentage="Math.ceil(item.exist_number/item.all_number*100)" class="w-50" />
              </div>
              <button v-if="projectIDState.hasOwnProperty(item.project_name)" class="btn btn-outline-primary ml-120 mt-80" disabled style="position: absolute;">{{projectIDState[item.project_name] }}</button>
              <button v-if="!  projectIDState.hasOwnProperty(item.project_name)" @click="open(item.project_id,item.project_name)" class="btn btn-outline-primary ml-120 mt-80" style="position: absolute;">申请</button>
          </div>
        </el-carousel-item>
      </el-carousel>
      <RouterView></RouterView>

    </el-tab-pane>
  </el-tabs>
</template>
<script  setup>
import axios from 'axios';
import { ref,reactive, watch} from 'vue'
import {  useRoute,useRouter } from 'vue-router';
import moment from 'moment';
import { ElMessage, ElMessageBox } from 'element-plus'
import { useChatwebsocketStore } from '@/store/chatwebsocket';

const drawer = ref(false)
const student_name=sessionStorage.getItem("user_name")
const activeName = ref('first')
const route=useRoute()
const router=useRouter()
const student_id=route.query.student_id
let college=route.query.college
let user_id=route.query.user_id
let user_name=sessionStorage.getItem("user_name")
let dialogMessage=ref({})
let dialogMessageStu=ref({})
let inputMessage=ref("")
let message=reactive({
  message_id:"",
  sender_id:user_id,  
  send_time:"",
  receiver_id:"",
  content:"",
  system:false,
  watch:false,
  sender_name:user_name,
  online:false
})
let application=reactive({
     projectapply_id:"",
     project_id:"",
     student_id:"",
     student_name:"",
     apply_time:"",
     apply_state:"",
     project_name:"",
})

let teacherList=ref([])
const getTeacherList=async()=>{
  let result=await axios({
    method:"get",
    url:"http://localhost:8080/getTeachersByCollege",
    params:{
      college:college
    }
  })
  return result.data
}
teacherList.value=await getTeacherList()

let studentList=ref([])
const getStudentList=async()=>{
  let result=await axios({
    method:"get",
    url:"http://localhost:8080/getStudentsByCollege",
    params:{
      college:college
    }
  })
  return result.data
}
studentList.value=await getStudentList()

//根据传进来的ID判断是不是本人发送的消息
function isSelf(id){
  if(id==user_id){
    return "row-col-1 mt-1 d-flex flex-row-reverse"
  }
  else{
    return "row-col-1 mt-1 d-flex"
  }
}
const websocketStore=useChatwebsocketStore()
//点开界面之后，自动建立websocket连接
const getconnection=async()=>{
  websocketStore.changeIsClear()
  let ws=new WebSocket("ws://localhost:8080/message/"+user_id);
  return ws
}
let ws=await getconnection()



let receiverId=ref("")
//消息列表
let messageList=ref({})
//得到聊天框
function getChatWindow(receiver_id,name){
  messageList.value[name]=[]
  dialogMessage.value[name]=true
  receiverId.value=receiver_id
}

function getChatWindStu(receiver_id,name){
  messageList.value[name]=[]
  dialogMessageStu.value[name]=true
  receiverId.value=receiver_id
}

ws.onmessage=function(evt){
   //告知全局，数据库数据变化
   websocketStore.changeIsConnected()
  //将消息JSON化存入pinia中
  websocketStore.setMessage(JSON.parse(evt.data))
  let tempMess=JSON.parse(evt.data)
  if(tempMess.sender_id==receiverId.value && tempMess.receiver_id==user_id){
    messageList.value[tempMess.sender_name].push(JSON.parse(evt.data))
  }
}
//发送按钮绑定发送消息的功能：将message对象JSON化
function sendMessageToService(receiver_id,receiver_name){
  // //告知全局，数据库数据变化
  // websocketStore.changeIsConnected()
  //设置消息的接受者
  message.receiver_id=receiver_id
  message.receiver_name=receiver_name
  message.sender_name=user_name
  message.send_time=moment().format('YYYY-MM-DD HH:mm:ss')
  //将用户输入的消息放进message中
  message.content=inputMessage.value
  ws.send(JSON.stringify(message))
  message.send_time=moment().format('YYYY-MM-DD HH:mm:ss')
  messageList.value[receiver_name].push(JSON.parse(JSON.stringify(message)))
  inputMessage.value=""
}
function setDialog(name){
  dialogMessage.value[name]=false
}
function setDialogStu(name){
  dialogMessageStu.value[name]=false
}
watch(route,()=>{
  let projectPath=route.fullPath.split('?')[0]
  let projectQuery=route.query
  router.push({path:'/index/jump',query:{user_id:user_id}})
  if(college!==projectQuery.college){
    setTimeout(() => {
      router.push({path:projectPath,query:projectQuery})
    }, 0.001);
  }
  
})

//科创项目
//根据学院获取该学院的所有大创信息
const getProjectByCollege=async()=>{
  let result=await axios({
    method:"get",
    url:"http://localhost:8080/getProjectByCollege",
    params:{
      college:college
    }
  })
  return result.data
}
let projectList=await getProjectByCollege()
//键值对 project_id->apply_state
let projectIDState=ref({})
//根据学生的ID获取这个学生所有的大创信息
const getProjectByStudentID=async()=>{
  let result=await axios({
    method:"get",
    url:"http://localhost:8080/getApplicationByStudentID",
    params:{
      student_id:student_id
    }
  })
  let list=result.data
  console.log(list)
  //遍历赋值
  for(let i=0;i<list.length;i++){
    projectIDState.value[list[i].project_name]=list[i].apply_state
  }
  return result.data
}
let studentProjectList=await getProjectByStudentID()


const open = (id,name) => {
  application.project_id=id
  application.project_name=name
  application.student_id=student_id
  application.student_name=student_name
  application.apply_time=moment().format('YYYY-MM-DD HH:mm:ss')
  ElMessageBox.alert('是否申请'+name, '提示', {
    confirmButtonText: '确定',
    callback:async () => {
      //给后端发送post请求,新建一个申请
      let isSuccess=await axios.post("http://localhost:8080/addApplication",application)
      if(isSuccess){
        ElMessage({
        type: 'success',
        message:"提交成功",
      })
      //重新赋一下值
      studentProjectList=await getProjectByStudentID()
      }
    },
  })
}

 //告知全局发送消息了
</script>


<style>
.demo-tabs > .el-tabs__content {
  padding:20px 0;
}
.el-carousel__item h3 {
  color: #475669;
  opacity: 0.75;
  line-height: 80px;
  margin: 0;
  text-align: center;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}
.demo-progress .el-progress--line {
  margin-bottom: 15px;
  max-width: 600px;
}
</style>

